/**
 * 账单地设置
 */

angular.module('inspinia',['uiSwitch','angularFileUpload']).controller('accountAddressCtrl',function(i18nService,$scope,$http,$state,FileUploader,$stateParams,$compile,$filter,$log,$uibModal,SweetAlert){
    $scope.paginationOptions=angular.copy($scope.paginationOptions);
    $scope.accountAddressTaskOptions=angular.copy($scope.paginationOptions);

    i18nService.setCurrentLang('zh-cn');  //设置语言为中文

    $scope.accountAreaMappings = [];
    $scope.accountAddressTask = [];
    $scope.accountAreaAddInfo = {openStatus:1,joinGroupPolling:1,province:"请选择",city:"请选择",postCard:[]};
    $scope.accountOperType = 1;

    $scope.allProvinceSelect = [{text:"请选择",value:""}];

    $scope.allCitySelect = [{text:"请选择",value:""}];

    $scope.accountAreaStatus = [{"text":"打开","value":1},{"text":"关闭","value":0}]
    $scope.joinGroupPollingStatus = [{"text":"不参与","value":1},{"text":"参与","value":0}]

    $scope.addressType=[{text:"是",value:1},{text:"否",value:0}];

    $scope.addressGroup = [{}];
    $scope.addressSettingId;
    $scope.address;

    $scope.addAddressGroup = function(event){
        $scope.addressGroup.push({});
    }

    $scope.deleteAddressGroup = function(index){
        $scope.addressGroup.splice(index, 1);
    }

    $scope.addAccountAddressQuota = function(){
        SweetAlert.swal({
                title: "我已确认账单地额度设置无误？",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    var effectiveTimeAarr = [];
                    for(var index in $scope.addressGroup) {
                        var item = $scope.addressGroup[index];
                        if(!item.totalAmount || !item.effectiveTime){
                            $scope.notice("请填写完整账单地额度信息");
                            return ;
                        }
                        $scope.addressGroup[index].effectiveTime = $scope.addressGroup[index].effectiveTime;
                        $scope.addressGroup[index].accountAddressId = $scope.addressSettingId;
                        $scope.addressGroup[index].address = $scope.address;
                        for(x in effectiveTimeAarr){
                            if($scope.addressGroup[index].effectiveTime == effectiveTimeAarr[x]){
                                $scope.notice("生效时间不能重复");
                                effectiveTimeAarr = [];
                                return ;
                            }
                        }
                        effectiveTimeAarr.push($scope.addressGroup[index].effectiveTime);
                    }
                    var formData = {
                        address : $scope.address,
                        addressGroup : $scope.addressGroup
                    }
                    $http.post("accountAddress/saveAddress.do",angular.toJson(formData)).success(function(data){
                        if(data.status){
                            $('#accountAreaSetting').modal('hide');
                            $scope.notice(data.msg);
                        } else {
                            $scope.notice(data.msg);
                        }
                    });
                    $scope.addressGroup = [{}];
                }
            });
    }

    $scope.getAddressSetting = function(id,address){
        $scope.addressSettingId = id;
        $scope.address = address;
        $http.get('accountAddress/findAddressSetting.do?id='+id).success(function(result){
            if(result.status) {
                if(result.data){
                    if(result.data.length > 0){
                        $scope.addressGroup = [];
                    }
                    for(i=0;i<result.data.length;i++){
                        var data = result.data[i];
                        $scope.addressGroup.push({id:data.id,totalAmount:data.totalAmount,effectiveTime:data.effectiveTimeStr,status:data.status});
                    }
                }
            }
        });
    };


    $scope.accountAreaSetting = function(row){
        var id = row.entity.id;
        var address = row.entity.address;
        $scope.getAddressSetting(id,address);
        $scope.getAccountAddressTaskList();
        $('#accountAreaSetting').modal('show');
    }

    $scope.accountAreaGrid = {
        paginationPageSize:10,                  //分页数量
        paginationPageSizes: [10,20,50,100],	//切换每页记录数
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs: [
            {field: 'address',displayName: '账单地',width: 100},
            {field: 'addressType',displayName: '是否单列市',width: 120,cellFilter:"formatDropping:"+angular.toJson($scope.addressType)},
            {field: 'totalAmount',displayName: '账单地额度(元)',width: 150},
            {field: 'reservedAmount',displayName: '预留额度(万)',width: 150,cellTemplate:
                    '<span class="lh30">{{(row.entity.reservedAmount/10000).toFixed(2)}}</span>'},
            {field: 'releaseTime',displayName: '预留额度释放时间',width: 180,cellFilter:'date:"HH:mm:ss"'},
            {field: 'transTimeRange',displayName: '交易时间区间',width: 150,
                cellTemplate: '<span class="lh30">{{row.entity.startTime | date:"HH:mm:ss"}}-{{row.entity.endTime | date:"HH:mm:ss"}}</span>'},
            {field: 'transAmountRange',displayName: '交易金额区间',width: 150,
                cellTemplate: '<span class="lh30">{{row.entity.minAmount}}-{{row.entity.maxAmount}}</span>'},
            {field: 'joinGroupPolling',displayName: '不参与集群轮循',width: 150,
                cellTemplate:
                    '<span><switch class="switch switch-s" ng-model="row.entity.joinGroupPolling" ng-true-value="1" ng-false-value="0" ng-change="grid.appScope.joinGroupPollingSwitch(row.entity)" /></span></span>'},
            {field: 'openStatus',displayName: '启用状态',width: 150,
                cellTemplate:
                    '<span><switch class="switch switch-s" ng-model="row.entity.openStatus" ng-true-value="1" ng-false-value="0" ng-change="grid.appScope.statusSwitch(row.entity)" /></span></span>'},
            { field: 'id',displayName:'操作',width:180,pinnedRight:true, cellTemplate:
                    '<div class="lh30">'+
                    '<a ng-click="grid.appScope.updateAccountAreaInfo(row,rowRenderIndex)">修改</a> ' +
                    '<a ng-click="grid.appScope.accountAreaSetting(row)">设置</a> ' +
                    '</div>'
            }
        ],
        onRegisterApi : function(gridApi) {
            // $scope.accountAreaGridApi = gridApi;
            // $scope.accountAreaGridApi.core.refresh();
            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                $scope.paginationOptions.pageNo = newPage;
                $scope.paginationOptions.pageSize = pageSize;
                $scope.getAccountAreaMappings();
            });
        }
    };


    $scope.getAccountAreaMappings = function(){
        $http.get('accountAddress/getAccountAreaMappings.do'+"?pageNo="+$scope.paginationOptions.pageNo+"&pageSize="+$scope.paginationOptions.pageSize).success(function(data){
            if(data.result){
                for(i=0;i<data.result.length;i++){
                    data.result[i].releaseTime = data.result[i].releaseTimeStr;
                    data.result[i].startTime = data.result[i].startTimeStr;
                    data.result[i].endTime = data.result[i].endTimeStr;
                }
            }
            $scope.accountAreaGrid.totalItems = data.totalCount;
            $scope.accountAreaGrid.data = data.result;
        });
    };

    $scope.getAccountAreaMappings();


    $scope.accountAddressTaskGrid = {
        paginationPageSize:10,                  //分页数量
        paginationPageSizes: [10,20,50,100],	//切换每页记录数
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs: [
            {field: 'totalAmount',displayName: '账单地额度(元)',width: 150},
            {field: 'operator',displayName: '操作人',width: 150},
            {field: 'createTime',displayName: '操作时间',width: 180,cellFilter:'date:"yyyy-MM-dd HH:mm:ss"'},
            {field: 'effectiveTime',displayName: '生效时间',width: 180,cellFilter:'date:"yyyy-MM-dd HH:mm:ss"'},
        ],
        onRegisterApi : function(gridApi) {
            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                $scope.accountAddressTaskOptions.pageNo = newPage;
                $scope.accountAddressTaskOptions.pageSize = pageSize;
                $scope.getAccountAddressTaskList();
            });
        }
    };


    $scope.getAccountAddressTaskList = function(){
        $http.get('accountAddress/getAccountAddressTaskList.do?accountAddressId='+$scope.addressSettingId+"&pageNo="+$scope.accountAddressTaskOptions.pageNo+"&pageSize="+$scope.accountAddressTaskOptions.pageSize).success(function(data){
            $scope.accountAddressTaskGrid.totalItems = data.totalCount;
            $scope.accountAddressTaskGrid.data = data.result;
        });
    };

    $scope.accountAreaSettingCancel = function(){
        $scope.addressGroup = [{}];
        $('#accountAreaSetting').modal('hide');
    }

    $scope.toLimit = function(item,fieldName,oldValue){
        if(item[fieldName]){
            if(/^\d*(\.\d{0,2})?$/.test(item[fieldName])==false){
                item[fieldName] = oldValue;
            }
        }
    };

    $scope.addAccountAreaInfo = function(){
        if(Number($scope.accountAreaAddInfo.maxAmount) <= Number($scope.accountAreaAddInfo.minAmount)){
            $scope.notice("交易金额最小区间必须小于交易最大区间");
            return;
        }
        if($scope.accountAreaAddInfo.province == '请选择'){
            $scope.notice("请选择账单地");
            return ;
        }

        var toDay = moment(new Date()).format("YYYY-MM-DD");
        var time1 = toDay+" "+$scope.accountAreaAddInfo.startTime;
        var time2 = toDay+" "+$scope.accountAreaAddInfo.endTime;
        time1 = new Date(Date.parse(time1.replace(/-/g,   "/"))).getTime();
        time2 = new Date(Date.parse(time2.replace(/-/g,   "/"))).getTime();

        if(time1 > time2){
            $scope.notice("交易时间不允许跨天");
            return ;
        }

        var url = "accountAddress/save.do";
        if($scope.accountOperType == 2){
            url = "accountAddress/update.do";
        }

        $http.post(url,angular.toJson($scope.accountAreaAddInfo)).success(function(data){
            if(data.status){
                $scope.accountAreaCancel();
                $scope.notice(data.msg);
                $scope.getAccountAreaMappings();
            } else {
                $scope.notice(data.msg);
            }
        });
    };

    $scope.updateAccountAreaInfo=function (row,index) {
        debugger;
        $scope.accountAreaAddInfo = angular.copy(row.entity);
        $scope.accountAreaAddInfo.reservedAmount = ($scope.accountAreaAddInfo.reservedAmount / 10000).toFixed(2);
        var province = $scope.accountAreaAddInfo.province;
        $http.get('areaInfo/getCityByProvince?province='+province).success(function(result){
            $scope.allCitySelect = [{text:"请选择",value:""}];
            if(result.status) {
                if(result.data==null || result.data.length==0){
                    $scope.allCitySelect.push({text:"请选择",value:""});
                }else{
                    for(var i in result.data){
                        $scope.allCitySelect.push({text:result.data[i].name,value:result.data[i].id});
                    }
                }
            }
        });
        if($scope.accountAreaAddInfo.addressType != 1){
            $scope.accountAreaAddInfo.city = "请选择";
        }
        $scope.accountAreaShow(2);
    }


    $scope.statusSwitch=function(entity){
        var title="";
        var status=0;
        if(entity.openStatus==false){
            title="确认关闭?"
        }else{
            title="确认开启?"
            status=1;
        }
        SweetAlert.swal({
                title:title,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "提交",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    entity.openStatus = status;
                    $http.get('accountAddress/updateOpenStatus?id='+entity.id+"&status="+status).success(function(result){
                    });
                }else{
                    $scope.callBackOpenSwitch(entity);
                }
            });
    };

    $scope.callBackOpenSwitch=function (entity) {
        if(entity.openStatus==false){
            entity.openStatus=1;
        }else{
            entity.openStatus=0;
        }
    };


    $scope.joinGroupPollingSwitch=function(entity){
        debugger;
        var title="";
        var status=0;
        if(entity.joinGroupPolling==false){
            title="确认参与?"
        }else{
            title="确认不参与?"
            status=1;
        }
        SweetAlert.swal({
                title:title,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "提交",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    entity.joinGroupPolling = status;
                    $http.get('accountAddress/updateJoinGroupPollingStatus?id='+entity.id+"&status="+status).success(function(result){
                    });
                }else{
                    $scope.callBackJoinGroupPollingSwitch(entity);
                }
            });
    };

    $scope.callBackJoinGroupPollingSwitch=function (entity) {
        if(entity.joinGroupPolling==false){
            entity.joinGroupPolling=1;
        }else{
            entity.joinGroupPolling=0;
        }
    };

    $scope.accountAreaShow = function(type){
        $scope.accountOperType = type;
        if(type == 1){
            $scope.accountAreaAddInfo = {};
            $scope.accountAreaAddInfo = {openStatus:1,joinGroupPolling:1,province:"请选择",city:"请选择"};
        }
        $('#accountAreaAdd').modal('show');
    }

    $scope.accountAreaCancel = function(){
        $('#accountAreaAdd').modal('hide');
    }

    $scope.getAllProvince = function(){
        //获取所有省份
        $http.get('areaInfo/getAllProvince').success(function(result){
            if(result.status) {
                if(result.data==null || result.data.length==0){
                    $scope.allProvinceSelect.push({text:"请选择",value:""});
                }else{
                    for(var i in result.data){
                        $scope.allProvinceSelect.push({text:result.data[i].name,value:result.data[i].id});
                    }
                }
            }
        });
    }
    $scope.getAllProvince();

    $scope.provinceChannge = function(){
        var province = $scope.accountAreaAddInfo.province;
        if(!province || province == "请选择"){
            $scope.accountAreaAddInfo.city = "请选择";
            $scope.allCitySelect = [];
            $scope.allCitySelect.push({text:"请选择",value:""});
        }else{
            $scope.getCity(province);
        }
    }

    $scope.getCity = function(province){
        $scope.allCitySelect = [];
        $scope.allCitySelect.push({text:"请选择",value:""});
        $scope.accountAreaAddInfo.city = "请选择";
        $http.get('areaInfo/getCityByProvince?province='+province).success(function(result){
            if(result.status) {
                if(result.data==null || result.data.length==0){
                    $scope.allCitySelect.push({text:"请选择",value:""});
                }else{
                    for(var i in result.data){
                        $scope.allCitySelect.push({text:result.data[i].name,value:result.data[i].id});
                    }
                }
            }
        });
    }

    $scope.minDate = function(){
        var curTime = new Date();
        var newHours = curTime.setHours(curTime.getHours() + 1);
        return moment(newHours).format("YYYY-MM-DD HH:00:00");
    }


    $scope.importAMShow = function(){
        $('#importAM').modal('show');
    }

    $scope.importAMCancel = function(){
        $('#importAM').modal('hide');
    }


    //上传图片,定义控制器路径
    var uploader1 = $scope.uploader1 = new FileUploader({
        url: 'accountAddress/accountAddressMappingImport',
        queueLimit: 1,   //文件个数
        removeAfterUpload: true,  //上传后删除文件
        headers : {'X-CSRF-TOKEN' : $scope.csrfData}
    });
    //过滤长度，只能上传一个
    uploader1.filters.push({
        name: 'isFile',
        fn: function(item, options) {
            return this.queue.length < 1;
        }
    });

    $scope.clearItems = function(){  //重新选择文件时，清空队列，达到覆盖文件的效果
        uploader1.clearQueue();
    }

    //导入
    $scope.importAddressMapping=function(){
        $scope.submitting = true;
        uploader1.uploadAll();//上传
        uploader1.onSuccessItem = function(fileItem, response, status, headers) {//上传成功后的回调函数，在里面执行提交
            if(response.status){
                $scope.getAccountAreaMappings();
                $scope.notice(response.msg);
                $scope.importAMCancel();
            }else{
                $scope.notice(response.msg);
            }
            $scope.submitting = false;
        };
    }


    $scope.accountAddressExport=function(){
        SweetAlert.swal({
                title: "确认导出？",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "提交",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    $scope.exportInfoClick("accountAddress/accountAreaMappingsExport.do");
                }
            });
    }
});